package com.itheima.d6_safe;

/**
 * 线程任务类，负责：取钱
 */
public class MyRunnable implements Runnable {

    private Account account;

    public MyRunnable(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        //开始取钱
        //1.判断余额是否足够
        if (account.getBalance() >= 100000) {
            //休眠一下，让另一个线程有机会抢到cpu的执行权
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //2.条件成立，余额充足
            //取钱：获取余额 - 100000，把新的余额赋值回去
            int oldBalance = account.getBalance();
            int newBalance = oldBalance - 100000;
            account.setBalance(newBalance);
            System.out.println(Thread.currentThread().getName() + "取钱成功，取了100000元");
        } else {
            System.out.println("取钱失败，余额不足！");
        }
        System.out.println("余额：" + account.getBalance() + "元");
    }
}
